package com.salefinder.server.server.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.salefinder.server.server.exception.DataNotFoundException;
import com.salefinder.server.server.exception.SystemException;
import com.salefinder.server.server.util.Constant;
import com.salefinder.server.server.vo.User;

public class UserDao extends BaseDao{

	public void createUser(User vo){
		this.create(vo);
	}
	
	public void deleteUser(User vo){
		this.delete(vo);
	}
	
	public User loadUser(User vo){
		vo = (User) this.load(this.getClass(), vo.getId());
		return vo;
	}
	
	public User getUserByUserIdNPassword(User vo) throws DataNotFoundException, SystemException{
		try{
			Session session = this.getSessionFactory().openSession();

			List userlist = session.createCriteria(User.class)
		    .add( Restrictions.eq("userId", vo.getUserId()))
		    .add( Restrictions.eq("password", vo.getPassword()))
		    .list();
			
			vo = (User) userlist.get(0);
			session.close();

			}catch(ArrayIndexOutOfBoundsException e){
				throw new DataNotFoundException(Constant.USER_NOT_FOUND, "User not found");
			
			}catch(Exception e){
				throw new SystemException(Constant.SYSTEM_ERROR,"System error creating user", e);
			}
			return vo;
	}
	
	public static void main(String [] args){
		User c = new User();
		c.setUserId("first");
		c.setPassword("first");
		UserDao cd = new UserDao();
		try {
			cd.getUserByUserIdNPassword(c);
		} catch (DataNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
